package cn.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/1 16:37
 */
@Setter
@Getter
@Component
//@PropertySource("application.yml")
@ConfigurationProperties("jwt.config")
public class JWTUtils {
    private String key; //私钥
    private Long ttl;  //签名的失效时间

    /**
     * 设置签发token
     * @param id  登录用户id  手机号
     * @param subject 登录用户名
     * @param map
     * @return
     */
    public String createJWT(String id, String subject, Map<String, Object> map) {
        // 设置失效时间
        // 当前毫秒
        long now = System.currentTimeMillis();
        long exp = now + ttl;
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(subject).setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        // 根据map 设置claims
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }
        //jwtBuilder.setClaims(map);
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(exp));
        }
        // 创建token
        String token = jwtBuilder.compact();
         return token;
    }

    /**
     * 解析JWT
     * @param token
     * @return
     */
    public Claims parseJWT(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token).getBody();
        } catch (Exception e) {
        }
        return claims;
    }
}
